<?php defined('SYSPATH') or die('No direct script access.');

class Book_Category{

// Book_Category instances
protected static $_instance;

public static function instance()
{
	if ( ! isset(Book_Category::$_instance))
	{
		// Create a new session instance
		Book_Category::$_instance = new Book_Category();
	}

	return Book_Category::$_instance;
}

public function render_thumb($image_file_name)
{
	if (!$image_file_name)
	{
		header("Status: 400 类别图片不存在");
		exit;
	}
	$thumb_image_path = Kohana::$config->load('upload')->get('thumb_category').$image_file_name;
	if (!file_exists($thumb_image_path))
	{
		$category_image_path = Kohana::$config->load('upload')->get('category').$image_file_name;
		if (!file_exists($category_image_path))
		{
			header("Status: 400 类别图片不存在");
			exit;
		}
		else
		{
			$this->scare_image($category_image_path, $thumb_image_path);
		}
	}
	Image_Output::write($thumb_image_path);
}

public function scare_image($category_image_path, $thumb_image_path)
{
	try
	{ 
		$image = new Kohana_Image_GD($category_image_path);
		$max_width = Kohana::$config->load('upload')->get('max_thumb_width');
		$max_height = Kohana::$config->load('upload')->get('max_thumb_height');
		if ($image->width > $max_width OR  $image->height > $max_height)
		{
			$image->resize($max_width, $max_height, Image::AUTO);
		}
		$image->save($thumb_image_path, 75);
	} 
	catch (Kohana_Exception $e)
	{
		header("Status: 400 类图片格式错误");
		exit;
	}
}

public function create_category_list($array)
{
	$object = array();
	foreach ( $array as $category)
	{
		if ($category->booklets->count_all() > 0)
		{
			array_push($object,
				array(
					'id'			=> $category->id,
					'name'  		=> $category->name
				));
		}
	}
	return array(
		'count' => count($object),
		'data'  => $object
	);
}

public function get_booklet_count($category)
{
	return ORM::factory('booklet')->where('category_id', '=', $booklet->id)->count_all();
}

}


